<template>
  <div id="home">
    <el-container style="overflow-y:hidden;overflow-x:hidden;">
      <el-scrollbar
        style="height:100%;white-space: nowrap;"
        @mousewheel.native="menuwheel"
        ref="homewheel"
        class="homewheel"
      >
        <!-- 滚动条组件 -->
        <el-menu
          class="el-menu-vertical-demo"
          background-color="#545c64"
          text-color="#fff"
          :default-active="this.$route.path"
          router
          :unique-opened="!isCollapse"
          :collapse="isCollapse"
        >
          <!-- 左边菜单栏 -->
          <template v-for="(item, index) in label">
            <!-- template是没任何属性的标签不会影响布局 -->
            <el-menu-item
              :index="item.index"
              :key="index"
              v-if="item.array == null"
              @click="array(item)"
            >
              <i class="el-icon-s-home"></i>
              <span slot="title">{{ item.text }}</span>
            </el-menu-item>
            <el-submenu
              :index="item.index"
              :key="index"
              v-if="item.array != null"
            >
              <template slot="title">
                <i :class="item.icon"></i>
                <span slot="title">{{ item.text }}</span>
              </template>
              <el-menu-item
                :index="item.index"
                v-for="(item, index) in item.array"
                :key="index"
                @click="array(item)"
                >{{ item.text }}</el-menu-item
              >
            </el-submenu>
          </template>
        </el-menu>
      </el-scrollbar>

      <!-- 左边菜单栏结束 -->
      <el-container style="height:100%;" class="main">
        <el-header style="overflow-y:hidden;overflow-x:hidden;">
          <!-- 右边头部 -->
          <div class="header-left">
            <div @click="fold()">
              <!-- 水平折叠收起菜单 -->
              <i class="el-icon-s-fold" id="fold"></i>
            </div>
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <!-- 面包屑 -->
              <el-breadcrumb-item to="/homepage">首页</el-breadcrumb-item>
              <el-breadcrumb-item v-for="item in breadcrumb" :key="item">{{
                item
              }}</el-breadcrumb-item>
            </el-breadcrumb>
            <!-- 面包屑结束 -->
          </div>
          <div class="header-right">
            <!-- 右上角内容 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="全屏"
              placement="bottom-end"
            >
              <i class="iconfont icon-quanping" @click="handleFullScreen"></i>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="字体大小"
              placement="bottom"
            >
              <i class="iconfont icon--zitidaxiao"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" placement="bottom">
              <div slot="content">换肤</div>
              <el-color-picker
                v-model="theme"
                popper-class="theme-picker-dropdown"
                class="theme-picker"
              ></el-color-picker>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="中英文切换"
              placement="bottom-end"
            >
              <i class="iconfont icon-zhongyingwen" @click="switchLang"></i>
            </el-tooltip>
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                <i class="iconfont icon-huanfu"></i>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>首页</el-dropdown-item>
                <el-dropdown-item @click.native="logOut()"
                  >退出登录</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
            <!-- 右上角内容结束 -->
          </div>
        </el-header>
        <el-main>
          <!-- 主要内容开始 -->
          <el-container style="height:100%;overflow-y:hidden;">
            <el-header style="height:37px">
              <!-- 主要内容的头部开始 -->
              <TagPage :tags="tags"></TagPage>
            </el-header>
            <el-main>
              <router-view />
            </el-main>
          </el-container>
          <!-- 主要内容结束 -->
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { mapState } from "vuex";
import TagPage from "../components/TagPage";
import Cookies from "js-cookie";
import screenfull from "screenfull";

const version = require("element-ui/package.json").version; // element-ui version from node_modules
const ORIGINAL_THEME = "#409EFF"; // default color
export default {
  data() {
    return {
      isCollapse: false, //控制是否只保持一个子菜单的展开和是否水平折叠收起菜单
      theme: ORIGINAL_THEME,
      breadcrumb: [], //面包屑数组
      tags: [], //传给子组件的数据
    };
  },
  components: {
    TagPage,
  },
  created: function() {
    //刷新后跳到对应页面
    for (let index = 0; index < this.$router.options.routes.length; index++) {
      //寻找对应的一级text
      if (
        this.$router.options.routes[index].path ==
        this.$router.currentRoute.matched[0].path
      ) {
        this.breadcrumb.push(this.$router.options.routes[index].name);
        if (this.$route.path == "/goods/upsert") {
          this.breadcrumb.push(this.$route.name);
          this.tags.push({ text: this.$route.name, index: this.$route.path });
        }
      }
    }
    for (let i in this.label) {
      //寻找对应的二级text
      if (this.label[i].array == null) {
        //判断刷新后是否是首页
        if (this.label[i].index == this.$router.currentRoute.path) {
          this.tags.push(this.label[i]);
        }
      } else {
        for (let j in this.label[i].array) {
          if (this.label[i].array[j].index == this.$router.currentRoute.path) {
            this.breadcrumb.push(this.label[i].array[j].text);
            this.tags.push(this.label[i].array[j]);
          }
        }
      }
    }
  },
  computed: {
    ...mapState(["lang"]),
    label() {
      return this.$t("items"); //$t里面写的是中英文中data的数据应用
    },
  },
  methods: {
    fold() {
      //水平折叠收起菜单的方法
      this.isCollapse = !this.isCollapse; //改变折叠收起的变量
      let fold = document.getElementById("fold"); //获取点击图标
      if (this.isCollapse) {
        //判断折叠收起的状态来改变点击图标
        fold.style.transform = "rotate(540deg)";
      } else {
        fold.style.transform = "rotate(0deg)";
      }
    },
    array(item) {
      //在数组中添加指定字符串的方法
      let that = this; //改变this指向
      let bool = true; //判断数组中是否有相同的东西
      for (let i = 0; i < that.tags.length; i++) {
        if (that.tags[i].text == item.text) {
          bool = false;
        }
      }
      if (bool) {
        //判断是否添加
        that.tags.push(item);
      }
    },
    logOut() {
      //退出登录
      let that = this;
      Cookies.remove("data");
      this.$router.replace(
        "/login?returnUrl=" + that.$router.app._route.fullPath
      );
    },
    switchLang() {
      //中英文切换
      let lang = "";
      if (this.lang === "en") {
        lang = "cn";
      } else {
        lang = "en";
      }
      this.$store.commit("switchLang", lang);
    },
    handleFullScreen() {
      //全屏
      screenfull.toggle();
    },
    updateStyle(style, oldCluster, newCluster) {
      let newStyle = style;
      oldCluster.forEach((color, index) => {
        newStyle = newStyle.replace(new RegExp(color, "ig"), newCluster[index]);
      });
      return newStyle;
    },

    getCSSString(url, callback, variable) {
      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
          this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, "");
          callback();
        }
      };
      xhr.open("GET", url);
      xhr.send();
    },

    getThemeCluster(theme) {
      const tintColor = (color, tint) => {
        let red = parseInt(color.slice(0, 2), 16);
        let green = parseInt(color.slice(2, 4), 16);
        let blue = parseInt(color.slice(4, 6), 16);

        if (tint === 0) {
          // when primary color is in its rgb space
          return [red, green, blue].join(",");
        } else {
          red += Math.round(tint * (255 - red));
          green += Math.round(tint * (255 - green));
          blue += Math.round(tint * (255 - blue));

          red = red.toString(16);
          green = green.toString(16);
          blue = blue.toString(16);

          return `#${red}${green}${blue}`;
        }
      };

      const shadeColor = (color, shade) => {
        let red = parseInt(color.slice(0, 2), 16);
        let green = parseInt(color.slice(2, 4), 16);
        let blue = parseInt(color.slice(4, 6), 16);

        red = Math.round((1 - shade) * red);
        green = Math.round((1 - shade) * green);
        blue = Math.round((1 - shade) * blue);

        red = red.toString(16);
        green = green.toString(16);
        blue = blue.toString(16);

        return `#${red}${green}${blue}`;
      };

      const clusters = [theme];
      for (let i = 0; i <= 9; i++) {
        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))));
      }
      clusters.push(shadeColor(theme, 0.1));
      return clusters;
    },
    menuwheel(e) {
      //滚动事件
      e = e || window.event;
      if (e.wheelDelta) {
        if (e.wheelDelta < 0) {
          //控制滚动的方向
          //向下
          this.$refs.homewheel.wrap.scrollTop += 20;
        } else {
          this.$refs.homewheel.wrap.scrollTop -= 20;
        }
      }
    },
    monitor(data) {
      //路由监听
      if(data.path=="/emptypage"){//空页面
        return
      }
      let res = this.tags.find((item) => {
        return item.index == data.path;
      });
      if (!res) {
        this.tags.push({ text: data.name, index: data.path });
      }
      for (let i in this.tags) {
        if (this.tags[i].index == data.path) {
          //监听对应的路由的面包蟹
          if (this.tags[i].text != "首页") {
            //判断监听的是首页
            if (this.breadcrumb.length == 0) {
              //判断数组是否有数据
              this.breadcrumb.push(data.matched[0].name);
              this.breadcrumb.push(this.tags[i].text);
            } else {
              if (this.$route.path == "/goods/upsert") {
                this.breadcrumb.splice(
                  0,
                  this.breadcrumb.length,
                  "商品管理",
                  "商品编辑"
                );
              } else {
                this.breadcrumb.splice(
                  0,
                  this.breadcrumb.length,
                  data.matched[0].name,
                  this.tags[i].text
                );
              }
            }
          } else {
            this.breadcrumb.splice(0, this.breadcrumb.length);
          }
        }
      }
    },
  },
  watch: {
    $route: "monitor",
    deep: true,
    theme(val, oldVal) {
      if (typeof val !== "string") return;
      const themeCluster = this.getThemeCluster(val.replace("#", ""));
      const originalCluster = this.getThemeCluster(oldVal.replace("#", ""));
      const getHandler = (variable, id) => {
        return () => {
          const originalCluster = this.getThemeCluster(
            ORIGINAL_THEME.replace("#", "")
          );
          const newStyle = this.updateStyle(
            this[variable],
            originalCluster,
            themeCluster
          );

          let styleTag = document.getElementById(id);
          if (!styleTag) {
            styleTag = document.createElement("style");
            styleTag.setAttribute("id", id);
            document.head.appendChild(styleTag);
          }
          styleTag.innerText = newStyle;
        };
      };

      const chalkHandler = getHandler("chalk", "chalk-style");

      if (!this.chalk) {
        const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`;
        this.getCSSString(url, chalkHandler, "chalk");
      } else {
        chalkHandler();
      }

      const styles = [].slice
        .call(document.querySelectorAll("style"))
        .filter((style) => {
          const text = style.innerText;
          return (
            new RegExp(oldVal, "i").test(text) && !/Chalk Variables/.test(text)
          );
        });
      styles.forEach((style) => {
        const { innerText } = style;
        if (typeof innerText !== "string") return
        style.innerText = this.updateStyle(
          innerText,
          originalCluster,
          themeCluster
        );
      });
      this.$message({
        message: "换肤成功",
        type: "success",
      });
    },
  },
};
</script>

<style lang="less" scoped>
// 媒体查询开始
@media (max-width: 800px) {
  .icon-quanping {
    display: none;
  }
}
@media (max-width: 755px) {
  .icon--zitidaxiao {
    display: none;
  }
  .el-breadcrumb span:nth-child(3) {
    display: none;
  }
  .main.el-container.is-vertical {
    width: 50%;
  }
}
@media (max-width: 600px) {
  .icon-huanfu {
    display: none;
  }
  //  .el-container{
  //   width: 40%;
  // }
}
@media (max-width: 550px) {
  .icon-zhongyingwen {
    display: none;
  }
  .el-breadcrumb span:nth-child(2) {
    display: none;
  }
}
@media (max-width: 400px) {
  .main.el-container.is-vertical {
    width: 5%;
  }
}
@media (max-width: 350px) {
  .main.el-container.is-vertical {
    width: 0%;
  }
}
// 媒体查询结束
.el-menu-vertical-demo:not(.el-menu--collapse) {
  //左边菜单栏
  width: 200px;
  min-height: 100vh;
}
.main {
  width: 70%;
}
.el-container {
  // width: 100%;
  height: 100vh;
}
.el-header {
  //右边头部
  background-color: #fdfcf7;
  color: #333;
  line-height: 18px;
  padding: 0px;
  display: flex;
  justify-content: space-between;
  flex-wrap: nowrap;
  align-items: center;
  border-bottom: #dcdfe6 1px solid;
}
.header-left {
  display: flex;
  align-items: center;
}
.iconfont {
  //图标
  margin: 0px 10px;
  font-size: 30px;
}
.el-aside {
  background-color: #d3dce6;
  color: #333;
  text-align: center;
  line-height: 200px;
  text-align: unset;
}
.el-main {
  //主要内容开始
  background-color: #e9eef3;
  color: #333;
  // text-align: center;
  line-height: 160px;
  padding: 0px;
}
.el-menu {
  //左边菜单栏
  border: 0px;
}
#fold {
  //水平折叠收起菜单
  transition: transform 0.8s;
  font-size: 25px;
}
.el-breadcrumb {
  //面包屑
  margin-left: 20px;
  font-size: 20px;
  display: flex;
  align-items: center;
}
.el-tag {
  margin: 0px 10px;
}
.el-menu-vertical-demo {
  height: 100vh;
}
.header-right {
  display: flex;
  align-items: center;
}
</style>

<style>
.homewheel .el-scrollbar__wrap {
  overflow-x: hidden;
}
</style>
